package net.sudot.chess.listener;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sudot.chess.business.model.Customer;
import net.sudot.chess.business.model.DepositRecord;
import net.sudot.chess.business.model.PointRecord;
import net.sudot.chess.business.model.SocialUser;
import net.sudot.chess.business.model.User;
import net.sudot.chess.business.service.CustomerService;
import net.sudot.chess.business.service.SocialUserService;
import net.sudot.chess.business.wechat.api.WechatApiService;
import net.sudot.chess.config.SystemProperties;
import net.sudot.commons.security.event.UserLoggedInEvent;
import net.sudot.commons.security.event.UserLoggedOutEvent;
import net.sudot.commons.security.event.UserRegisteredEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 用户事件监听器
 *
 * @author tangjialin on 2018-03-17.
 */
@Component
public class UserEventListener {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SystemProperties systemProperties;
    @Resource
    private CustomerService customerService;
    @Resource
    private SocialUserService socialUserService;
    @Resource
    private WechatApiService wechatApiService;

    /**
     * 用户注册事件处理
     *
     * @param userRegisteredEvent 用户注册事件
     */
    @EventListener
    public void handle(UserRegisteredEvent userRegisteredEvent) {
        User user = (User) userRegisteredEvent.getUser();
        if (user instanceof Customer) {
            Customer customer = (Customer) user;
            BigDecimal registerBalance = systemProperties.getRegisterBalance();
            if (registerBalance.compareTo(BigDecimal.ZERO) > 0) {
                customerService.addBalance(customer, registerBalance, DepositRecord.Type.REWARD, "注册赠送");
            }
            int registerPoint = systemProperties.getRegisterPoint();
            if (registerPoint > 0) {
                customerService.addPoint(customer, registerPoint, PointRecord.Type.REWARD, "注册赠送");
            }
        }
    }

    /**
     * 用户登录事件处理
     *
     * @param userLoggedInEvent 用户登录事件
     */
    @EventListener
    public void handle(UserLoggedInEvent userLoggedInEvent) {
        User user = (User) userLoggedInEvent.getUser();
//        HttpServletRequest request = WebUtils.getRequest();
//        HttpServletResponse response = WebUtils.getResponse();

        if (user instanceof Customer) {
            Customer customer = (Customer) user;
            if (customer.getHead() != null) { return; }
            SocialUser socialUser = socialUserService.findByUser(wechatApiService.getWxMpConfigStorage().getAppId(), customer.getId());
            if (socialUser == null || !socialUser.isSubscribe()) { return; }
            try {
                /**
                 * 未关注公众号返回信息:
                 * WxMpUser[
                 *   subscribe=false
                 *   openId=openId
                 *   sex=未知
                 *   tagIds={}
                 * ]
                 * 已关注公众号返回信息:
                 * WxMpUser[
                 *   subscribe=true
                 *   openId=openId
                 *   nickname=微信昵称
                 *   sex=男
                 *   language=zh_CN
                 *   city=深圳
                 *   province=广东
                 *   country=中国
                 *   headImgUrl=http://thirdwx.qlogo.cn/mmopen/xxxx/132
                 *   subscribeTime=时间戳
                 *   sexId=1
                 *   remark=
                 *   groupId=0
                 *   tagIds={}
                 * ]
                 */
                WxMpUser wxMpUser = wechatApiService.getUserService().userInfo(socialUser.getUniqueId());
                customer.setHead(wxMpUser.getHeadImgUrl());
                customer.setNickname(wxMpUser.getNickname());
                customerService.update(customer);
            } catch (WxErrorException e) {
                logger.warn("会员微信信息获取失败:{}", e.getMessage());
            } catch (Exception e) {
                logger.warn("会员微信信息获取失败", e);
            }
        }

    }

    /**
     * 用户登出事件处理
     *
     * @param userLoggedOutEvent 用户登出事件
     */
    @EventListener
    public void handle(UserLoggedOutEvent userLoggedOutEvent) {
    }
}